import Foundation
import Moya
import Combine

class APIService {
    private let provider: MoyaProvider<MultiTarget>
    
    init() {
        provider = MoyaProvider<MultiTarget>(plugins: [NetworkLoggerPlugin()])
    }
    
    // 泛型请求方法
    func request<T: Decodable>(_ target: TargetType, type: T.Type) -> AnyPublisher<T, Error> {
        let target = MultiTarget(target)
        
        return provider
            .requestPublisher(target)
            .tryMap { response -> T in
                // 验证请求是否成功
                guard (200...299).contains(response.statusCode) else {
                    throw MoyaError.statusCode(response)
                }
                return try JSONDecoder().decode(T.self, from: response.data)
            }
            .receive(on: DispatchQueue.main)
            .eraseToAnyPublisher()
    }
}
